package net.vanchu.mortgagecalculator.mortgage.calculate;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dtspread.apps.houseloan.R;
import com.dtspread.libs.push.PushJumpHandleActivity;
import com.dtspread.libs.share.ShareController;
import com.dtspread.libs.share.util.ShareUtil;
import com.dtspread.libs.upgrade.UpgradeLogic;
import com.dtspread.libs.util.StatusBarUtil;
import com.vanchu.dropdownview.component.ListDropDownView;

import net.vanchu.mortgagecalculator.common.CommonSoftKeyBoardHelper;
import net.vanchu.mortgagecalculator.common.commonView.call.PopupWindowHelper;
import net.vanchu.mortgagecalculator.common.config.AppConstant;
import net.vanchu.mortgagecalculator.common.config.LoanWay;
import net.vanchu.mortgagecalculator.moreApps.MoreAppsActivity;
import net.vanchu.mortgagecalculator.mortgage.calculate.mix.CalMixLoansFragment;
import net.vanchu.mortgagecalculator.mortgage.calculate.single.CalSingleLoansFragment;
import net.vanchu.mortgagecalculator.mortgage.data.repaymentSummary.RepaySummary;
import net.vanchu.mortgagecalculator.mortgage.help.MortgageHelpActivity;
import net.vanchu.mortgagecalculator.mortgage.resultShow.ResultShowActivity;
import net.vanchu.mortgagecalculator.mortgage.resultShow.ResultShowContract;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends PushJumpHandleActivity
        implements OnLoanWaySwitchListener, CalculateResultListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private HashMap<String, Boolean> visibilityMap = new HashMap<>();

    private ImageView imgMore;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("VISIBILITY_MAP", visibilityMap);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        visibilityMap = (HashMap<String, Boolean>) savedInstanceState.getSerializable("VISIBILITY_MAP");
        setVisibleWithMap(visibilityMap);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PopupWindowHelper.closeAll();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cal_loans);

        imgMore = (ImageView) findViewById(R.id.main_page_img_more);
        imgMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMoreOptionsMenu();
            }
        });

        StatusBarUtil.setColor(this, getResources().getColor(R.color.bg_pop_win_header));

        if (savedInstanceState == null) {
            onLoanWaySwitch(LoanWay.wayCommercial);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        UpgradeLogic.saveUpgradeBussinessWhenPaused();
    }

    @Override
    protected void onResume() {
        super.onResume();
        UpgradeLogic.activeUpgradeBusinessWhenResumed();
    }

    private void setVisibleWithMap(HashMap<String, Boolean> visibilityMap) {
        Boolean visible = visibilityMap.get(CalSingleLoansFragment.class.getSimpleName());
        Boolean visibleMixPage = visibilityMap.get(CalMixLoansFragment.class.getSimpleName());

        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (Fragment fragment : fragments) {
            if (fragment == null) {
                continue;
            }
            if (fragment.getClass().getSimpleName().equals(CalSingleLoansFragment.class.getSimpleName())) {
                if (visible) {
                    getSupportFragmentManager().beginTransaction().show(fragment).commit();
                } else {
                    getSupportFragmentManager().beginTransaction().hide(fragment).commit();
                }
            }
            if (fragment.getClass().getSimpleName().equals(CalMixLoansFragment.class.getSimpleName())) {
                if (visibleMixPage) {
                    getSupportFragmentManager().beginTransaction().show(fragment).commit();
                } else {
                    getSupportFragmentManager().beginTransaction().hide(fragment).commit();
                }
            }
        }
    }

    @Override
    public void onLoanWaySwitch(LoanWay loanWay) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        CalMixLoansFragment calMixLoanPage = (CalMixLoansFragment) findFragmentByClassName(CalMixLoansFragment.class.getSimpleName());
        CalSingleLoansFragment calSingleLoanPage = (CalSingleLoansFragment) findFragmentByClassName(CalSingleLoansFragment.class.getSimpleName());

        if (calMixLoanPage != null) {
            transaction.hide(calMixLoanPage);
            visibilityMap.put(calMixLoanPage.getClass().getSimpleName(), false);
        }
        if (calSingleLoanPage != null) {
            transaction.hide(calSingleLoanPage);
            visibilityMap.put(calSingleLoanPage.getClass().getSimpleName(), false);
        }

        if (loanWay == LoanWay.wayMix) {
            if (calMixLoanPage == null) {
                calMixLoanPage = new CalMixLoansFragment();
                transaction.add(R.id.container, calMixLoanPage);
                visibilityMap.put(calMixLoanPage.getClass().getSimpleName(), true);
            } else {
                transaction.show(calMixLoanPage);
                visibilityMap.put(calMixLoanPage.getClass().getSimpleName(), true);
            }
        } else {
            if (calSingleLoanPage == null) {
                calSingleLoanPage = new CalSingleLoansFragment();
                transaction.add(R.id.container, calSingleLoanPage);
                visibilityMap.put(calSingleLoanPage.getClass().getSimpleName(), true);
            } else {
                transaction.show(calSingleLoanPage);
                visibilityMap.put(calSingleLoanPage.getClass().getSimpleName(), true);
                calSingleLoanPage.getArguments().putSerializable(CalSingleLoansFragment.WAY, loanWay);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    private Fragment findFragmentByClassName(String clazzName) {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments == null) {
            return null;
        }
        if (fragments.size() == 0) {
            return null;
        }
        for (Fragment fragment : fragments) {
            if (fragment == null) {
                continue;
            }
            if (fragment.getClass().getSimpleName().equals(clazzName)) {
                return fragment;
            }
        }
        return null;
    }

    @Override
    public void onSingleWayCalculateResult(RepaySummary.Single repaySummary) {
        Intent intent = new Intent();
        intent.setClass(this, ResultShowActivity.class);
        intent.putExtra(ResultShowContract.SINGLE_REPAY_SUMMARY_KEY, repaySummary);
        startActivity(intent);
    }

    @Override
    public void onMixWayCalculateResult(RepaySummary.Mix repaySummary) {
        Intent intent = new Intent();
        intent.setClass(this, ResultShowActivity.class);
        intent.putExtra(ResultShowContract.MIX_REPAY_SUMMARY_KEY, repaySummary);
        startActivity(intent);
    }

    @Override
    protected void handleJump(String s) {
        Log.i(TAG, "handleJump: " + s);
    }

    private void showMoreOptionsMenu() {
        CommonSoftKeyBoardHelper.checkSoftKeyBoard(imgMore);
        ListDropDownView.Builder<StrAndIconData> builder = new ListDropDownView.Builder<>(imgMore);
        builder.setDropItemAdapter(
                new ListDropDownView.DropItemAdapter<StrAndIconData>(StrAndIconData.getMoreOptionItems(this)) {
                    @Override
                    public int getItemLayoutId() {
                        return R.layout.item_more_options;
                    }

                    @Override
                    public void bind(View itemView, StrAndIconData data) {
                        TextView textView = (TextView) itemView.findViewById(R.id.item_more_opts_tv);
                        ImageView imageView = (ImageView) itemView.findViewById(R.id.item_more_opts_ic);
                        imageView.setImageResource(data.iconRes);
                        textView.setText(data.str);
                    }
                });
        builder.setItemClickListener(new ListDropDownView.ItemClickListener<StrAndIconData>() {
            @Override
            public boolean onItemClick(int position, StrAndIconData data) {
                if (data.iconRes == R.drawable.ic_mortgage_knowledge) {
                    jump2HelpPage();
                    return false;
                }
                if (data.iconRes == R.drawable.ic_other_apps) {
                    jumpToMoreApps();
                    return false;
                }
                if (data.iconRes == R.drawable.ic_share_to_friends) {
                    prepareShare();
                    return false;
                }
                return false;
            }
        });
        ListDropDownView<StrAndIconData> listDropDownView = builder.create();
        listDropDownView.show(5, 10);
    }

    private void prepareShare() {
        ShareController shareController = new ShareController(MainActivity.this, "from");
        String title = "计算房贷就用它——2016最新房贷计算器";
        String content = "房贷不知道怎么算？房贷计算器帮你轻松计算、明白理财！";
        ShareUtil.prepareToShare(shareController, title, content, AppConstant.ICON_URL, AppConstant.URL_SHARE_APP);
        shareController.showShareBoard();
    }

    private void jump2HelpPage() {
        Intent intent = new Intent();
        intent.setClass(this, MortgageHelpActivity.class);
        intent.putExtra(MoreAppsActivity.INTENT_TITLE, getString(R.string.mortgage_knowledge));
        intent.putExtra(MoreAppsActivity.INTENT_URL, AppConstant.URL_HELP);
        startActivity(intent);
    }

    private void jumpToMoreApps() {
        Intent intent = new Intent();
        intent.setClass(this, MoreAppsActivity.class);
        intent.putExtra(MoreAppsActivity.INTENT_TITLE, getString(R.string.more_apps));
        intent.putExtra(MoreAppsActivity.INTENT_URL, AppConstant.URL_APP_WALL);
        startActivity(intent);
    }

    private boolean exit = false;

    @Override
    public void onBackPressed() {
        if (exit) {
            super.onBackPressed();
        } else {
            exit = true;
            Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 2000);
        }
    }

    private static class StrAndIconData {
        String str;
        int iconRes;

        StrAndIconData(String str, int iconRes) {
            this.str = str;
            this.iconRes = iconRes;
        }

        static List<StrAndIconData> getMoreOptionItems(Context context) {
            List<StrAndIconData> strAndIconDatas = new ArrayList<>();
            strAndIconDatas.add(new StrAndIconData(context.getString(R.string.more_apps), R.drawable.ic_other_apps));
            strAndIconDatas.add(new StrAndIconData(context.getString(R.string.mortgage_knowledge), R.drawable.ic_mortgage_knowledge));
            strAndIconDatas.add(new StrAndIconData(context.getString(R.string.share_to_friends), R.drawable.ic_share_to_friends));
            return strAndIconDatas;
        }
    }
}